package com.toommi.refuse.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.toommi.refuse.common.enums.FamilyRoleEnum;
import com.toommi.refuse.entity.*;
import com.toommi.refuse.enums.WechatUserExceptionEnum;
import com.toommi.refuse.exception.WechatUserException;
import com.toommi.refuse.mapper.*;
import com.toommi.refuse.model.WechatUserModel;
import com.toommi.refuse.service.WechatUserService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangg
 * @since 2019-07-24 17:16
 */
@Service
@AllArgsConstructor
public class WechatUserServiceImpl implements WechatUserService {

    private WechatUserMapper wechatUserMapper;

    private WechatUserHouseholdMapper userHouseholdMapper;

    private AreaMapper areaMapper;

    private NeighbourhoodMapper neighbourhoodMapper;

    private BuildingMapper buildingMapper;

    private HouseholdMapper householdMapper;

    @Override
    public Map<String, Object> updateUser(String openid, String username, String phone, String code) throws WechatUserException {
        //验证手机号验证码格式
        if (!StringUtils.isNumeric(phone) || phone.length() > 11) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_PHONE_NULL);
        }
        if (StringUtils.isEmpty(code)) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_VERIFYCODE_NULL);
        }
        if (StringUtils.isEmpty(username)) {
            throw new WechatUserException(WechatUserExceptionEnum.INVlLID_USERNAME_FORMAT);
        }

        //验证当前用户是否存在,用户需先关注授权，数据会存入
        Map<String, Object> user = wechatUserMapper.getUserInfoByOpenId(openid);
        if (user != null) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_REPEAT);
        }

        //验证手机号是否已被使用

        WechatUser wechatUser = new WechatUser();
        wechatUser.setPhone(phone);

        if (wechatUserMapper.selectCount(wechatUser) > 0) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_PHONE_REPEAT);
        }
        Map<String, Object> userinfo = new HashMap<String, Object>();
        userinfo.put("time", System.currentTimeMillis());
        userinfo.put("openid", openid);
        userinfo.put("username", username);
        userinfo.put("phone", phone);
        userinfo.put("code", code);
        wechatUserMapper.updateWeiXinUser(userinfo);
        return userinfo;
    }

    @Override
    public PageInfo<WechatUserModel> getUsers(int pageSize, int currentPage, String keyWord) {
        PageHelper.startPage(currentPage, pageSize);
        List<WechatUser> wechatUserList = wechatUserMapper.selectAll();
        List<WechatUserModel> wechatUserModels = new ArrayList<>(wechatUserList.size());
        for (WechatUser wechatUser : wechatUserList) {
            WechatUserModel userModel = new WechatUserModel();
            BeanUtils.copyProperties(wechatUser, userModel);
            wechatUserModels.add(userModel);
        }
        return new PageInfo<>(wechatUserModels);
    }

    @Override
    public void bindAddress(WechatUserHousehold wechatUserHousehold) throws WechatUserException {
//        String openid=request.getParameter("openid");
//        String cityname="重庆市";
//        String xxname=request.getParameter("xxname");
//        String xxid=request.getParameter("xxid");
//        String jdname=request.getParameter("jdname");
//        String jdid=request.getParameter("jdid");
//        String xqname=request.getParameter("xqname");
//        String xqid=request.getParameter("xqid");
//        String dh=request.getParameter("dh");
//        String mph=request.getParameter("mph");
        Map<String, Object> wechatUser1 = wechatUserMapper.getUserInfo(wechatUserHousehold.getWechatUserId());
        WechatUser wechatUser = new WechatUser();
        wechatUser.setId(Long.valueOf(String.valueOf(wechatUser1.get("id"))));
        wechatUser.setPhone(String.valueOf(wechatUser1.get("phone")));
        wechatUser.setName(String.valueOf(wechatUser1.get("name")));
        wechatUser.setOpenId(String.valueOf(wechatUser1.get("open_id")));
        if (wechatUser == null) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_NULL);
        }
        //门牌号
        Household household = householdMapper.selectByPrimaryKey(wechatUserHousehold.getHouseholdId());
        if (household == null) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_ADDRESS);
        }
        //校验用户是否已绑定过
        WechatUserHousehold wechatUserHousehold1 = new WechatUserHousehold();
        wechatUserHousehold1.setWechatUserId(wechatUserHousehold.getWechatUserId());

        if (userHouseholdMapper.selectCount(wechatUserHousehold1) > 0) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_ADDRESS_AGAIN);
        }
        //检查该门牌号是否被绑定过

        WechatUserHouseholdExample example = new WechatUserHouseholdExample();
        example.createCriteria().andHouseholdIdEqualTo(wechatUserHousehold.getHouseholdId());
        if (userHouseholdMapper.selectCountByExample(example) <= 0) {
            wechatUserHousehold.setRole(FamilyRoleEnum.MASTER.getCode());
        } else {
            wechatUserHousehold.setRole(FamilyRoleEnum.SLAVE.getCode());
        }


        //保存用户与门牌号关系
        wechatUserHousehold.setCreateTime(System.currentTimeMillis());
        wechatUserHousehold.setUpdateTime(System.currentTimeMillis());
        userHouseholdMapper.insert(wechatUserHousehold);
        //拼接完整的地址避免多表级联查询，以空间换时间

        Building building = buildingMapper.selectByPrimaryKey(household.getBuilding());
        if (building == null) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_ADDRESS);
        }
        Neighbourhood neighbourhood = neighbourhoodMapper.selectByPrimaryKey(building.getNeighbourhood());
        if (neighbourhood == null) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_ADDRESS);
        }
        Area street = areaMapper.selectByPrimaryKey(neighbourhood.getStreet());
        Area district = areaMapper.selectByPrimaryKey(neighbourhood.getDistrict());

        if (street == null || district == null) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_ADDRESS);
        }
        //完整的居住地址
        String address = district.getName() + street.getName() +
                neighbourhood.getName() + building.getName() + household.getName();
        wechatUser.setAddress(address);
        wechatUser.setUpdateTime(System.currentTimeMillis());
        wechatUser.setCreateTime(System.currentTimeMillis());
        wechatUserMapper.updateByPrimaryKey(wechatUser);
        // wechatUserMapper.updateWsWeiXinUser(openid,cityname,xxname,xxid,jdname,jdid,xqname,xqid,dh,mph);
    }

    @Override
    public void addUser(WechatUserModel wechatUserModel) throws WechatUserException {
        //openid必须唯一

        if (StringUtils.isEmpty(wechatUserModel.getOpenId())) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_OPENID_NULL);
        }

        if (findUser(wechatUserModel.getOpenId()) != null) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_OPENID_REPEAT);
        }

        wechatUserModel.setId(0);
        wechatUserModel.setCreateTime(System.currentTimeMillis());
        wechatUserModel.setUpdateTime(System.currentTimeMillis());

    }

    @Override
    public WechatUser findUser(String openId) {

        WechatUser wechatUser = new WechatUser();
        wechatUser.setOpenId(openId);

        return wechatUserMapper.selectOne(wechatUser);
    }

    /**
     * 根据openid获取微信用户信息
     *
     * @param openid
     * @return
     */
    @Override
    public Map<String, Object> getUserInfo(String openid) {
        return wechatUserMapper.getUserInfo(openid);
    }

    /**
     * 获取用户二维码
     *
     * @param openid
     * @return
     */
    @Override
    public Object getUserQrcode(String openid) {
        return wechatUserMapper.getUserQrcode(openid);
    }

    /**
     * 判断二维码是否正确
     *
     * @param code
     * @return
     */
    @Override
    public Map<String, Object> judgeQrcode(String code) {
        Integer num = wechatUserMapper.judgeQrcode(code);
        //箱体的傻逼还需要用户信息，我查询返回给他们，一群傻吊，艹
        Map<String, Object> userinfo = wechatUserMapper.getUserInfoByCode(code);
        return userinfo;
    }

    @Override
    public Map<String, Object> getUserInfoByOpenId(String openid) {
        return wechatUserMapper.getUserInfoByOpenId(openid);
    }

    /**
     * 注册
     *
     * @param phone
     * @param password
     * @param id
     * @return
     */
    @Override
    public void register(String phone, String password, String id, String name) throws WechatUserException {
        //先判断这个号码时候已经被注册了
        Integer num = wechatUserMapper.checkPhone(phone);
        if (num > 0) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_PHONE_REPEAT);
        }
        //然后吧数据更新到表
        wechatUserMapper.register(phone, password, id, name);

    }

    /**
     * 登陆
     *
     * @param phone
     * @param password
     * @return
     * @throws WechatUserException
     */
    @Override
    public Object login(String phone, String password) throws WechatUserException {
        Map<String, Object> object = wechatUserMapper.login(phone, password);
        if (object == null) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_PASSWORD_NOTMATCH);
        }
        String status = String.valueOf(object.get("status"));
        if (!"1".equals(status)) {
            throw new WechatUserException(WechatUserExceptionEnum.INVALID_USER_OPENID_STATUS);
        }
        return object;
    }
}
